package drds.plus.common.model.hint;

import drds.plus.common.model.comparative.ColumnNameToComparativeMapChoicer;
import drds.plus.common.model.comparative.Comparative;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 基于tddl-rule的hint条件
 */
public class RuleRouteCondition extends ExtraCmdRouteCondition implements RouteCondition, ColumnNameToComparativeMapChoicer {

    private Map<String, Comparative> columnNameToComparativeMap = new HashMap<String, Comparative>();

    /**
     * 添加一个默认为=的参数对
     */
    public void put(String key, Comparable<?> parameter) {
        if (key == null) {
            throw new IllegalArgumentException("key为null");
        }
        if (parameter instanceof Comparative) {
            columnNameToComparativeMap.put(key.toLowerCase(), (Comparative) parameter);
        } else {
            columnNameToComparativeMap.put(key.toLowerCase(), getComparative(Comparative.equal, parameter));
        }

    }

    public Comparative getComparative(int i, Comparable<?> c) {
        return new Comparative(i, c);
    }

    public Map<String, Comparative> getColumnNameToComparativeMap(Set<String> columnNameSet, List<Object> argumentList) {
        Map<String, Comparative> columnNameToComparativeMap = new HashMap<String, Comparative>(this.columnNameToComparativeMap.size());
        for (String columnName : columnNameSet) {
            if (columnName != null) {
                // 因为groovy是大小写敏感的，因此这里只是在匹配的时候转为小写，放入map中的时候仍然使用原来的大小写
                Comparative comparative = this.columnNameToComparativeMap.get(columnName.toLowerCase());
                if (comparative != null) {
                    columnNameToComparativeMap.put(columnName, comparative);
                }
            }
        }
        return columnNameToComparativeMap;
    }

    public Comparative getColumnComparative(String columnName, List<Object> arguments) {
        Comparative comparative1 = null;
        if (columnName != null) {
            // 因为groovy是大小写敏感的，因此这里只是在匹配的时候转为小写，放入map中的时候仍然使用原来的大小写
            Comparative comparative = columnNameToComparativeMap.get(columnName.toLowerCase());
            if (comparative != null) {
                comparative1 = comparative;
            }
        }

        return comparative1;
    }

    public Map<String, Comparative> getColumnNameToComparativeMap() {
        return columnNameToComparativeMap;
    }

    public ColumnNameToComparativeMapChoicer getComparativeMapChoicer() {
        return this;
    }
}
